package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.ConsulConfig;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.contract.VendoutContract;
import com.lkd.contract.VendoutData;
import com.lkd.contract.VendoutResultContract;
import com.lkd.dao.OrderDao;
import com.lkd.feign.UserService;
import com.lkd.vo.*;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.OrderEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.service.OrderService;
import com.lkd.utils.DistributedLock;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Override
    public OrderEntity getByOrderNo(String orderNo) {
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(OrderEntity::getOrderNo, orderNo);
        return this.getOne(qw);
    }

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private MqttProducer mqttProducer;

    @Autowired
    private ConsulConfig consulConfig;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public OrderEntity createOrder(PayVO payVO) {
        Boolean hasCapacity = vmService.hasCapacity(payVO.getInnerCode(), Long.parseLong(payVO.getSkuId()));
        if (!hasCapacity) {
            throw new LogicException("该商品已售空");
        }
        DistributedLock lock = new DistributedLock(
                consulConfig.getConsulRegisterHost(),
                consulConfig.getConsulRegisterPort());
        DistributedLock.LockContext lockContext = lock.getLock("key",60);
        if(!lockContext.isGetLock()){
            throw new LogicException("机器出货中请稍后再试");
        }
        redisTemplate.boundValueOps( VMSystem.VM_LOCK_KEY_PREF+payVO.getInnerCode()+"_"+payVO.getSkuId() )
                .set(lockContext.getSession(), Duration.ofSeconds(60));//存入redis后是为了释放锁
        OrderEntity orderEntity = new OrderEntity();

        VmVO vmInfo = vmService.getVMInfo(payVO.getInnerCode());
        if (vmInfo == null) {
            throw new LogicException("该售货机不存在，参数错误");
        }
        BeanUtils.copyProperties(vmInfo, orderEntity);
        orderEntity.setAddr(vmInfo.getNodeAddr());

        SkuVO sku = vmService.getSku(payVO.getSkuId());
        if (sku == null) {
            throw new LogicException("该商品不存在，参数错误");
        }
        BeanUtils.copyProperties(sku, orderEntity);
        orderEntity.setAmount(sku.getRealPrice());

        PartnerVO partner = userService.getPartner(vmInfo.getOwnerId());
        if (partner == null) {
            throw new LogicException("该售货机合作商不存在，参数错误");
        }
        BigDecimal bg = new BigDecimal(sku.getRealPrice());
        int bill = bg.multiply(new BigDecimal(partner.getRatio())).divide(new BigDecimal(100), 0, RoundingMode.HALF_UP).intValue();
        orderEntity.setBill(bill);

        orderEntity.setOrderNo(payVO.getInnerCode() + System.nanoTime());
        orderEntity.setStatus(VMSystem.ORDER_STATUS_CREATE);
        orderEntity.setOpenId(payVO.getOpenId());
        orderEntity.setPayType("2");
        orderEntity.setPayStatus(VMSystem.PAY_STATUS_NOPAY);

        save(orderEntity);
        OrderCheck orderCheck = new OrderCheck();
        orderCheck.setOrderNo(orderCheck.getInnerCode());
        orderCheck.setOrderNo(orderEntity.getOrderNo());
        try {
            mqttProducer.send("$delayed/300/" + TopicConfig.ORDER_CHECK_TOPIC, 2, orderCheck);
            log.info("订单微服务设置失效时间发送消息成功");
        } catch (JsonProcessingException e) {
            log.info("订单微服务设置失效时间发送消息失败");
            throw new LogicException("订单微服务设置失效时间发送消息失败");
        }
        return orderEntity;
    }

    @Override
    public boolean vendOut(String orderNo, Long skuId, String innerCode) {
        //封装出货协议
        VendoutContract vendoutContract = new VendoutContract();
        VendoutData vendoutData = new VendoutData();
        vendoutData.setSkuId(skuId);
        vendoutData.setOrderNo(orderNo);
        vendoutContract.setInnerCode(innerCode);
        vendoutContract.setVendoutData(vendoutData);
        //发送到EMQ
        try {
            mqttProducer.send(TopicConfig.VMS_VENDOUT_TOPIC, 2, vendoutContract);
            return true;
        } catch (JsonProcessingException e) {
            log.error("订单微服务出货方法封装出货协议消息发送EMQ失败");
            return false;
        }
    }

    @Override
    public boolean vendOutResult(VendoutResultContract vendoutResultContract) {
        OrderEntity orderEntity = getByOrderNo(vendoutResultContract.getVendoutData().getOrderNo());
        if (vendoutResultContract.isSuccess()) {
            if (orderEntity == null) {
                log.error("订单不存在");
                return false;
            }
            log.info("订单出货成功，订单编号：{}", vendoutResultContract.getVendoutData().getOrderNo());
            orderEntity.setStatus(VMSystem.ORDER_STATUS_VENDOUT_SUCCESS);
            updateById(orderEntity);
            return true;
        } else {
            orderEntity.setStatus(VMSystem.ORDER_STATUS_VENDOUT_FAIL);
            orderEntity.setPayStatus(VMSystem.PAY_STATUS_REFUNDING);
            log.info("出货失败,开始退款");
            //todo :通知退款
            orderEntity.setPayStatus(VMSystem.PAY_STATUS_REFUNDED);
            updateById(orderEntity);
            return true;
        }
    }

}
